package com.cwx.web;

import com.alibaba.fastjson.JSONObject;
import com.cwx.common.Json;
import com.cwx.dao.entity.Member;
import com.cwx.interfaces.SMSInterface;
import com.cwx.service.MemberService;
import com.cwx.tools.CacheUtil;
import com.cwx.utils.Tool;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by code on 17-8-30.
 */
@Controller
public class IndexController {

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private MemberService memberService;

    @RequestMapping("/")
    public String index(HttpSession session)
    {
        if (session.getAttribute("member") != null){
            return "redirect:/toMain";
        }
        return "/index";
    }

    @GetMapping("/register")
    public String register(){
        return "/html/register";
    }

    @GetMapping("/login")
    public String login(){
        return "/login";
    }
    /**
     * 登录
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Json login(String phone, String password, String type,HttpSession session) {
        Json json = new Json();
        Member member = memberService.findByPhone(phone);
        if (member == null) {
            json.setCode("20007");
            json.setMessage("用户名不存在!");
        }
        else if (member.getPassword().equals(Tool.encoderByMd5(password + member.getSalt()))) {
            session.setAttribute("member",member);
            String openid = member.getOpenid();
            if (type != null && type.equals("wechat")){
                if (openid == null || openid.equals("")){
                    json.setCode("10012");
                    json.setMessage("提示用户绑定微信号!");
                }else {
                    json.setCode("10013");
                    json.setMessage("跳转至微信端主页");
                }
            }else {
                json.setCode("10004");
                json.setMessage("登陆成功!");
            }
        } else {
            json.setCode("20008");
            json.setMessage("用户名或密码错误!");
        }
        return json;
    }

    @RequestMapping("/toMain")
    public String toMain(){
        return "/html/personal";
    }

    /**
     * 注册(检验手机验证码)
     * @param phone
     * @param password
     * @param codeParam
     * @param session
     * @return
     */
    @ResponseBody
    @PostMapping("/register")
    public Json register(String phone, String password, String codeParam, HttpSession session) {
        Json json = new Json();
        Object code = session.getAttribute("code");
        if (code != null && codeParam != null && code.toString().equals(codeParam)) {
            Member queryMember = memberService.findByPhone(phone);
            if (queryMember != null){
                json.setCode("20009");
                json.setMessage("您的手机号已注册!");
                return json;
            }
            Member member = new Member();
            member.setPhone(phone);
            member.setPassword(password);
            memberService.save(member);
            json.setCode("10001");//register success
            json.setMessage("注册成功!");
            cacheUtil.evict(phone);
        } else {
            json.setCode("20006");//code erro
            json.setMessage("请输入正确的短信验证码!");
            return json;
        }
        return json;
    }

    /**
     * 下发短信验证码
     * @param phone
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendSms")
    public Json sendSms(String phone, HttpSession session) {
        Json json = new Json();
        try {
            Object object = cacheUtil.getCacheElement(phone);
            if (object != null) {
                JSONObject pullJson = (JSONObject) JSONObject.toJSON(object);
                int count = pullJson.getInteger("count");
                long lastTime = pullJson.getLong("sendTime");
                long currentTime = System.currentTimeMillis();
                long time = (currentTime - lastTime) / 1000;
                if (time <= 60) {
                    json.setCode("20004");//time small
                    json.setMessage("请不要在一分钟内重复下发短信!");
                    return json;
                }
                if (count >= 5) {
                    json.setCode("20005");//toMany num
                    json.setMessage("今日短信次数已用完,请明天再试");
                    return json;
                }
                pullJson.put("count", count + 1);
                pullJson.put("sendTime", System.currentTimeMillis());
                cacheUtil.addToCache(phone, pullJson);
            } else {
                JSONObject pushJson = new JSONObject();
                pushJson.put("count", 1);
                pushJson.put("sendTime", System.currentTimeMillis());
                cacheUtil.addToCache(phone, pushJson);
            }
            String code = String.valueOf(RandomUtils.nextInt(000000,999999));
            String resultStr = SMSInterface.sms(phone, "30460", "#code#=" + code);
            JSONObject result = JSONObject.parseObject(resultStr);
            int errorCode = result.getInteger("error_code");
            switch (errorCode) {
                case 0:
                    session.setAttribute("code", code);
                    json.setCode("10000");//suceeess
                    json.setMessage("短信下发成功!");
                    break;
                case 205401:
                    json.setCode("20001");//错误的手机号码
                    json.setMessage("错误的手机号码!");
                    break;
                case 205404:
                    json.setCode("20002");//发送失败，具体原因请参考返回reason
                    json.setMessage(result.getString("reason"));
                    break;
                case 205405:
                    json.setCode("20003");//号码异常/同一号码发送次数过于频繁
                    json.setMessage("号码异常/同一号码发送次数过于频繁!");
                    break;
                default:
                    json.setCode("20000");//网站异常,请稍后重试
                    json.setMessage("网站异常,请稍后重试!");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setCode("20000");//网站异常,请稍后重试
            json.setMessage("网站异常,请稍后重试!");
            return json;
        }

        return json;
    }

    /**
     * 检查手机号是否注册
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkPhone")
    public Json checkPhone(String phone){
        Json json = new Json();
        Member member = memberService.findByPhone(phone);
        if (member != null){
            json.setCode("20009");
            json.setMessage("您的手机号已注册!");
        }else {
            json.setCode("10002");
            json.setMessage("手机号尚未注册!");
        }
        return json;
    }



    /**
     * 找回密码&修改密码
     * @param phone
     * @param password
     * @param codeParam
     * @param session
     * @return
     */
    @RequestMapping("/retrievePwd")
    @ResponseBody
    public Json retrievePwd(String phone, String password, String codeParam, HttpSession session){
        Json json = new Json();
        Member member = memberService.findByPhone(phone);
        Object code = session.getAttribute("code");
        if (code != null && codeParam != null && code.toString().equals(codeParam)) {
            Member queryMember = memberService.findByPhone(phone);
            if (queryMember != null){
                queryMember.setPassword(Tool.encoderByMd5(password + member.getSalt()));
                memberService.retrievePwd(queryMember);
                session.setAttribute("memeber",member);
                json.setCode("10003");
                json.setMessage("密码修改成功!");
                cacheUtil.evict(phone);

            }else {
                json.setCode("10002");//register success
                json.setMessage("您的手机号尚未注册!");
            }
        } else {
            json.setCode("20006");//code erro
            json.setMessage("请输入正确的短信验证码!");
        }
        return json;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session,String type){
        session.removeAttribute("member");
        if (type.equals("wechat")){
            return "redirect:/wechat/toMain";
        }
        return "/index";
    }

}
